package com.v1.admin.manage;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants;

import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.v1.model.CategoryWapper;
import com.v1.model.ItemWapper;

@Service("photobucket")
public class PhotobucketFeed extends BaseFeed {

	public PhotobucketFeed() throws ParserConfigurationException {
		super();
	}

	public CategoryWapper parse(String url) throws Exception {
		Document document = builder.parse(new URL(url).openStream());
		Node root = (Node) xpath.evaluate("/rss/channel", document, XPathConstants.NODE);
		CategoryWapper category = parseCategory(root);
		NodeList medias = document.getElementsByTagName("media:content");
		List<ItemWapper> items = parseItems(medias);
		category.setItems(items);
		return category;
	}

	private List<ItemWapper> parseItems(NodeList entrys) throws UnsupportedEncodingException {
		int length = entrys.getLength();
		List<ItemWapper> items = new ArrayList<ItemWapper>();
		for (int i = 0; i < length; i++) {
			Node entry = entrys.item(i);
			ItemWapper item = parseItem(entry);
			items.add(item);
		}
		return items;
	}

	private ItemWapper parseItem(Node entry) throws UnsupportedEncodingException {
		ItemWapper item = new ItemWapper();
		String medium = getAttributeValue(entry, "medium");
		if (medium != null && "image".equals(medium)) {
			String url = getAttributeValue(entry, "url");
			item.setUrl(url);
		}

		NodeList childNodes = entry.getChildNodes();
		int length = childNodes.getLength();
		for (int i = 0; i < length; i++) {
			Node node = childNodes.item(i);
			String nodeName = node.getNodeName();
			if ("media:title".equals(nodeName)) {
				String nodeValue = node.getTextContent();
				String decode = StringEscapeUtils.unescapeHtml(nodeValue);
				item.setName(decode);
			} else if ("media:description".equals(nodeName)) {
				String nodeValue = node.getTextContent();
				String decode = StringEscapeUtils.unescapeHtml(nodeValue);
				item.setDigest(decode);
			} else if ("media:thumbnail".equals(nodeName)) {
				String nodeValue = getAttributeValue(node, "url");
				item.setThumb(nodeValue);
			}
		}
		return item;
	}

	private String getAttributeValue(Node node, String name) {
		NamedNodeMap attributes = node.getAttributes();
		if (attributes == null) {
			return null;
		}
		Node namedItem = attributes.getNamedItem(name);
		if (namedItem == null) {
			return null;
		}
		String nodeValue = namedItem.getNodeValue();
		return nodeValue;
	}

	private CategoryWapper parseCategory(Node node) {
		NodeList childNodes = node.getChildNodes();
		int length = childNodes.getLength();
		CategoryWapper category = new CategoryWapper();
		for (int i = 0; i < length; i++) {
			Node item = childNodes.item(i);
			String nodeName = item.getNodeName();
			if ("link".equals(nodeName)) {
				String link = item.getTextContent();
				category.setLink(link);
			}
		}
		return category;
	}

	/**
	 * @param args
	 * @throws DocumentException
	 * @throws URISyntaxException
	 * @throws MalformedURLException
	 */
	public static void main(String[] args) throws Exception {
		String fileName = "http://feed1057.photobucket.com/albums/t384/luyang_/vw-Touareg/feed.rss";
		new PhotobucketFeed().parse(fileName);

		/*
		 * SAXReader reader = new SAXReader(); String fileName =
		 * "http://feed1057.photobucket.com/albums/t384/luyang_/vw-Touareg/feed.rss"
		 * ; parse(fileName);
		 * 
		 * URL url = new URL(fileName); // Document document = reader.read(url);
		 * // Element link = (Element) ((Element) document.getRootElement() //
		 * .elements().get(8)).elements().get(9); // //
		 * link.getUniquePath()Path(); // List selectNodes =
		 * document.selectNodes("/feed/entry/link[@href]"); //
		 * System.out.println(link);
		 * 
		 * DocumentBuilder builder =
		 * DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document
		 * document = builder.parse(url.openStream()); XPath xpath =
		 * XPathFactory.newInstance().newXPath(); NodeList nodelist = (NodeList)
		 * xpath.evaluate("/feed/entry/link[@type=\"image/jpeg\"]", document,
		 * XPathConstants.NODESET); int length = nodelist.getLength(); for (int
		 * i = 0; i < length; i++) { Node item = nodelist.item(i); NamedNodeMap
		 * attributes = item.getAttributes(); Node namedItem =
		 * attributes.getNamedItem("href"); Object nodeValue =
		 * namedItem.getNodeValue(); System.out.println(nodeValue); } //
		 * System.out.println(nodelist);
		 */

	}
}
